<?php

namespace app\admin\controller\ykjp\inventory;

use app\common\controller\Backend;
use think\Db;

/**
 * 盘点单
 *
 * @icon fa fa-check
 */
class Procheck extends Backend {

    /**
     * Inventory模型对象
     * @var \app\admin\model\ykjp\inventory\Inventory
     */
    protected $model = null;

    // protected $distinguish=true;

    public function _initialize() {
        parent::_initialize();
        $this->model = new \app\admin\model\ykjp\inventory\Inventory;
        $this->view->assign("typeList", $this->model->getTypeList());
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index() {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            // if ($this->request->request('keyField')) {
            //     return $this->selectpage();
            // }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = Db::name('ykjp_check')
                    ->alias('c')
                    ->join('ykjp_product p', 'c.product_id = p.id')
                    ->where($where)
                    ->where("c.firmid", $this->auth->firmid)
                    ->order('c.id', $order)
                    ->count();
            $list = Db::name('ykjp_check')
                    ->alias('c')
                    ->join('ykjp_product p', 'c.product_id = p.id')
                    ->field('c.*,p.name,p.unit,p.prop,p.specification')
                    ->where($where)
                    ->where("c.firmid", $this->auth->firmid)
                    ->order('c.id', $order)
                    ->limit($offset, $limit)
                    ->select();
            $list = collection($list)->toArray();

            // 根据字段中储存的id，获取实际的值
            for ($i = 0; $i < count($list); $i++) {

                $w_id = $list[$i]['warehouse_id'];  //所在仓库id
                $p_id = $list[$i]['partition_id'];  //所在库区id

                $prop_list = json_decode($list[$i]['prop'], true);  //获取商品属性列表
                $prop = '';
                // 解析商品属性
                for ($j = 0; $j < count($prop_list); $j++) {
                    $prop .= $prop_list[$j]['title'] . ':' . $prop_list[$j]['value'] . ';';
                }
                $list[$i]['prop'] = $prop;  //商品属性
                //获取所在仓库名称
                $warehouse = Db::name('ykjp_warehouse')
                        ->field('name')
                        ->where("firmid", $this->auth->firmid)
                        ->where('id', $w_id)
                        ->find();
                $list[$i]['w_name'] = $warehouse['name'];

                //获取所在库区名称
                $partition = Db::name('ykjp_partition')
                        ->field('name')
                        ->where("firmid", $this->auth->firmid)
                        ->where('id', $p_id)
                        ->find();
                $list[$i]['p_name'] = $partition['name'];
            }
            //获取仓库
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加盘点单
     */
    public function add() {
        if ($this->request->isAjax()) {
            $request = $this->request->param();  //获取参数
            //验证参数
            if (!$request['row']['warehouse_id']) {
                $this->error('请选择仓库', null, null);
            } elseif (!$request['row']['partition_id']) {
                $this->error('请选择仓库分区', null, null);
            } elseif (!$request['row']['product_id']) {
                $this->error('请选择商品', null, null);
            } elseif (!$request['row']['number']) {
                $this->error('请输入盘点数量', null, null);
            }

            $warehouse_id = $request['row']['warehouse_id'];  //仓库ID
            $partition_id = $request['row']['partition_id'];  //库区ID
            $product_id = $request['row']['product_id'];      //产品ID
            $number = $request['row']['number'];              //流水数量
            $request['row']['updatetime'] = time();           //设置更新时间
            $request['row']['firmid'] = $this->auth->firmid;  //设置企业ID
            // 判断盘盈还是盘亏
            if ($request['row']['type'] == '盘盈入库') {
                $fun = 'setInc';  //TP5加值 方法
                $op = '+';
                $request['row']['real_num'] = $request['row']['surface_num'] + $number;
            } elseif ($request['row']['type'] == '盘亏出库') {
                $fun = 'setDec';  //TP5减值 方法
                $op = '-';
                $request['row']['real_num'] = $request['row']['surface_num'] - $number;
                //判断盘亏数量是否大于当前账目数量
                if ($request['row']['real_num'] < 0) {
                    $this->error('盘亏数量不得大于当前账目数量！', null, null);
                }
            }

            //提交数据（插入盘点表->插入流水表->更新关联表->更新商品表->更新仓库表->更新库区表）
            // 启动事务
            Db::startTrans();
            try {

                //插入盘点表
                Db::name('ykjp_check')->insert($request['row']);

                unset($request['row']['real_num']);  //移除流水表不需要的实际库存
                unset($request['row']['surface_num']);  //移除流水表不需要的账目库存
                //插入流水表
                Db::name('ykjp_inventory_statement')->insert($request['row']);

                //更新关联表 
                $data['inventory'] = array('exp', 'inventory' . $op . $number);
                $data['updatetime'] = time();
                Db::name('ykjp_wp_relationship')->where(['warehouse_id' => $warehouse_id, 'partition_id' => $partition_id, 'product_id' => $product_id])->where("firmid", $this->auth->firmid)->update([
                    'updatetime' => time(),
                    'inventory' => Db::raw('inventory' . $op . $number),
                ]);

                //更新商品表
                Db::name('ykjp_product')->where("firmid", $this->auth->firmid)->where('id', $product_id)->$fun('inventory', $number);

                //更新仓库表
                Db::name('ykjp_warehouse')->where("firmid", $this->auth->firmid)->where('id', $warehouse_id)->$fun('inventory', $number);

                //更新库区表
                Db::name('ykjp_partition')->where("firmid", $this->auth->firmid)->where('id', $partition_id)->$fun('inventory', $number);

                // 提交事务
                Db::commit();
                $this->success('提交成功', null, null);
            } catch (PDOException $e) {

                Db::rollback();
                $this->error('提交失败');
            } catch (Exception $e) {

                Db::rollback();
                $this->error('提交失败');
            }
        }
        return $this->view->fetch('add');
    }

    /**
     * 获取仓库列表
     */
    public function warehouse() {
        $warehouselist = Db::name('ykjp_warehouse')->where("firmid", $this->auth->firmid)->field('id as value,name')->order('id desc')->select();
        $this->success('', null, $warehouselist);
    }

    /**
     * 获取分区列表
     */
    public function partition() {
        $id = $this->request->request('id');
        $partitionlist = Db::name('ykjp_partition')->where('warehouse_id', $id)->where("firmid", $this->auth->firmid)->field('id as value,name')->order('id desc')->select();
        $this->success('', null, $partitionlist);
    }

    /**
     * 获取产品列表
     */
    public function product() {
        $id = $this->request->request('id');
        $productlist = Db::name('ykjp_product')
                ->alias('p')
                ->join('ykjp_wp_relationship w', 'w.product_id = p.id')
                ->field('p.id as value,p.name')
                ->where('w.partition_id', $id)
                ->where("w.firmid", $this->auth->firmid)
                ->select();
        $this->success('', null, $productlist);
    }

    /**
     * 获取账面库存
     */
    public function get_surface_num() {
        $where = $this->request->param();
        $surface_num = Db::name('ykjp_wp_relationship')
                ->field('inventory')
                ->where($where)
                ->where("firmid", $this->auth->firmid)
                ->find();
        $this->success('', null, $surface_num);
    }

}
